package com.cet.spring_batch_study.utils;

import com.cet.spring_batch_study.annotations.CsvHeader;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.LinkedList;
import java.util.List;

/**
 * @author NSOC
 */
public class ConvertCsvDataUtil {

    public static  <T> String listToCsvData(List<T> data, Class<T> clazz) throws IllegalAccessException {

        LinkedList<Field> fields = new LinkedList<>();
        fields.addAll(List.of(clazz.getDeclaredFields()));
        // 多层可自己递归
        fields.addAll(List.of(clazz.getSuperclass().getDeclaredFields()));

        List<List<Object>> result = new LinkedList<>();

        LinkedList<Object> csvHeaderList = new LinkedList<>();

        for (Field field : fields) {
            CsvHeader csvHeader = field.getAnnotation(CsvHeader.class);
            if (csvHeader == null || csvHeader.name().isEmpty()) {
                throw new  RuntimeException();
            }
            csvHeaderList.add(csvHeader.name());
        }

        result.add(csvHeaderList);

        for (T row : data) {
            LinkedList<Object> dataRowList = new LinkedList<>();

            for (Field field : fields) {
                ReflectionUtils.makeAccessible(field);
                dataRowList.add(field.get(row));
            }
            result.add(dataRowList);
        }

        return format(result);
    }

    private static String format(List<List<Object>> result) {
        // todo:根据列表处理成自己要的输出格式
        return null;
    }
}
